package coder.taiji.spring;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * 功能:在 spring 启动的时候获保存 spring 的 context
 *
 * @author helloworldyu
 * 文件名称：AppContext.java
 * 创建日期: 2017/10/19
 */
public class SpringContext implements ApplicationContextAware {

	/**
	 * The spring application context.
	 */
	private static ApplicationContext applicationContext;

	/**
	 * 根据beanName获取bean
	 *
	 * @param beanName bean 的名字
	 * @return bean 对象
	 */
	public static Object getBean(String beanName) {
		if (null == beanName) {
			return null;
		}
		return applicationContext.getBean(beanName);
	}

	/**
	 * 根据类型获取 bean
	 *
	 * @param className class
	 * @param <T>       bean 对象的类型
	 * @return bean 对象
	 */
	public static <T> T getBean(Class<T> className) {
		if (null == className) {
			return null;
		}
		return applicationContext.getBean(className);
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		SpringContext.applicationContext = applicationContext;
	}
}